import 'package:aio/aio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:app/generated/app_strings.dart';
import 'package:app/src/config/app_data_cache.dart';
import 'package:app/src/http/bean/user.dart';
import 'package:app/src/manager/ywx_manager.dart';
import 'package:app/src/ui/app_ui.dart';
import 'package:app/src/http/bean/ywx_limit.dart';
import 'package:app/src/ui/dialog/dailog.dart';
import 'package:app/src/ui/route/helper/route_helper.dart';
import 'package:app/src/utils/image_path_utils.dart';

import '../../../../http/bean/worksdo/material_requisition_bean.dart';
import '../../../../http/bean/wroks/dispatchingaudit_bean.dart';
import '../../../../http/model/material_requisition_model.dart';
import '../../../../http/model/review_model.dart';
import '../../../../http/model/user_model.dart';
import '../../../popuwindow/popuwindow_search.dart';

///背景色
Color backgroundColor() {
  return AppColors.backgroundColorWithWhite;
}

///申请人搜索
class SearchApplyNameRoute extends StatefulWidget {
  @override
  _State createState() => _State();
  ResponseCallbackWithT responseCallbackWithT;

  SearchApplyNameRoute(this.responseCallbackWithT);
}

class _State extends State<SearchApplyNameRoute> {
  _Presenter presenter = _Presenter();

  @override
  void initState() {
    super.initState();
    presenter?.getDatas(context, (value) {});
  }

  @override
  Widget build(BuildContext context) {
    px.init(context);
    var scaffold = Scaffold(
      backgroundColor: backgroundColor(),
      appBar: AppBar(
        //fixme 搜索框位置
        backgroundColor: backgroundColor(),
        elevation: 0,
        leading: AppUi.getBack(context, () {
          return false;
        }),
        leadingWidth: 33,
        titleSpacing: 0,
        title: Text(
          AppStrings.of(context)
              .ApplySearch2, //ApplySearch2 人员搜索(改成这个，更通用)，ApplySearch 申请人搜索；
          style: TextStyle(color: Colors.black),
        ),
      ),
      body: Material(
          color: backgroundColor(),
          child: Column(
            children: [
              _department(context),
              SizedBox(
                height: 8,
              ),
              _searchName(context),
              SizedBox(
                height: 8,
              ),
              _searchJobNumber(context),
              _addItemWithBtn(context, onPressed: () {
                presenter?.getDatas(context, (value) {
                  setState(() {});
                });
              }),
              Expanded(child: _body(context))
            ],
          )),
    );
    var willPopScope = WillPopScope(
      child: scaffold,
      onWillPop: () async {
        return true; //true 不屏蔽返回键
      },
    );
    return Material(child: willPopScope, color: backgroundColor());
  }

  ///部门搜索
  Widget _department(BuildContext context) {
    return _addItemWithTextClick(
        context, AppStrings.of(context).department, presenter?.departmentName,
        onTap: (valueNotifier) {
      presenter.getdepartment(context, (value) {
        var datas = value;
        var department = Department();
        department.DeptName = "";
        department.DeptId = "";
        department.key = "";
        department.value = "";
        datas.insert(0, department); //第一位插入一个空值
        // datas.add(RollerBean(key: '1', value: '陆清波'));
        // datas.add(RollerBean(key: '2', value: '朱高怀'));
        // datas.add(RollerBean(key: '3', value: '叶勇'));
        // datas.add(RollerBean(key: '1', value: '黄定锋'));
        AppDialog.showDialogWithRollerPicker(context,
                datas: datas, value: valueNotifier.value)
            ?.then((value) {
          if (value != null && value!.value != null) {
            presenter.departmentId = value.key;
            presenter.departmentName = value.value;
            valueNotifier?.value = value!.value!; //更新数据
            setState(() {});
          }
        });
      });
    });
  }

  ///姓名搜索框
  Widget _searchName(BuildContext context) {
    Widget widget = StatefulBuilder(
      builder: (BuildContext context, StateSetter setState) {
        // presenter?.setStateSearch = setState;
        var textField = TextField(
          textAlign: TextAlign.start,
          textAlignVertical: TextAlignVertical.center,
          onChanged: (value) {
            //文本发生变化
            setState(() {
              presenter?.searName = value;
            });
            presenter?.setStateBody?.call(() {});
          },
          controller:
              TextUtils.setTextEditingController(text: presenter?.searName),
          autofocus: false,
          decoration: InputDecoration(
              //尾部删除图标
              suffixIcon: (presenter.searName!.length > 0)
                  ? Container(
                      width: 30,
                      height: 30,
                      child: InkWell(
                        child: Center(
                          child: Icon(
                            Icons.clear,
                            color: Colors.grey,
                            size: 16,
                          ),
                        ),
                        onTap: () {
                          //文本清除
                          setState(() {
                            presenter.searName = "";
                          });
                          presenter?.setStateBody?.call(() {});
                        },
                      ),
                    )
                  : null,
              prefixIcon: Icon(Icons.search, color: Colors.black),
              hintText: AppStrings.of(context).TheName,
              contentPadding: EdgeInsets.symmetric(horizontal: 4, vertical: 4),
              focusedBorder: OutlineInputBorder(
                  borderSide: BorderSide(
                      color: Colors.black, width: 1, style: BorderStyle.solid),
                  borderRadius: BorderRadius.all(Radius.circular(30.0))),
              border: OutlineInputBorder(
                  borderSide: BorderSide(
                      color: Colors.grey, width: 1, style: BorderStyle.solid),
                  borderRadius: BorderRadius.all(Radius.circular(30.0)))),
        );
        return SizedBox(
          child: textField,
          height: 30,
        );
      },
    );
    return Padding(
      padding: EdgeInsets.only(right: 16, top: 0, bottom: 0),
      child: widget,
    );
  }

  ///工号搜索框
  Widget _searchJobNumber(BuildContext context) {
    Widget widget = StatefulBuilder(
      builder: (BuildContext context, StateSetter setState) {
        // presenter?.setStateSearch = setState;
        var textField = TextField(
          textAlign: TextAlign.start,
          textAlignVertical: TextAlignVertical.center,
          onChanged: (value) {
            //文本发生变化
            setState(() {
              presenter?.JobNumber = value;
            });
            presenter?.setStateBody?.call(() {});
          },
          controller:
              TextUtils.setTextEditingController(text: presenter?.JobNumber),
          autofocus: false,
          decoration: InputDecoration(
              //尾部删除图标
              suffixIcon: (presenter.JobNumber!.length > 0)
                  ? Container(
                      width: 30,
                      height: 30,
                      child: InkWell(
                        child: Center(
                          child: Icon(
                            Icons.clear,
                            color: Colors.grey,
                            size: 16,
                          ),
                        ),
                        onTap: () {
                          //文本清除
                          setState(() {
                            presenter.JobNumber = "";
                          });
                          presenter?.setStateBody?.call(() {});
                        },
                      ),
                    )
                  : null,
              prefixIcon: Icon(Icons.search, color: Colors.black),
              hintText: AppStrings.of(context).JobNumber,
              contentPadding: EdgeInsets.symmetric(horizontal: 4, vertical: 4),
              focusedBorder: OutlineInputBorder(
                  borderSide: BorderSide(
                      color: Colors.black, width: 1, style: BorderStyle.solid),
                  borderRadius: BorderRadius.all(Radius.circular(30.0))),
              border: OutlineInputBorder(
                  borderSide: BorderSide(
                      color: Colors.grey, width: 1, style: BorderStyle.solid),
                  borderRadius: BorderRadius.all(Radius.circular(30.0)))),
        );
        return SizedBox(
          child: textField,
          height: 30,
        );
      },
    );
    return Padding(
      padding: EdgeInsets.only(right: 16, top: 0, bottom: 0),
      child: widget,
    );
  }

  //主体布局
  Widget _body(BuildContext context) {
    return StatefulBuilder(
      builder: (BuildContext context, StateSetter setState) {
        presenter?.setStateBody = setState;
        List<UserApplicant>? allItems = presenter?.datas;
        List<UserApplicant> searchItems = [];

        if (StringUtils.isNotEmpty(presenter.searName) ||
            StringUtils.isNotEmpty(presenter.departmentName) ||
            StringUtils.isNotEmpty(presenter.JobNumber)) {
          allItems?.forEach((element) {
            bool b1 =
                (element.PersonName?.contains(presenter?.searName ?? "") ??
                    false);
            bool b2 =
                (element.DeptName?.contains(presenter?.departmentName ?? "") ??
                    false);
            bool b3 =
                (element.PersonCode?.contains(presenter?.JobNumber ?? "") ??
                    false);
            if (b1 && b2 && b3) {
              if (!searchItems.contains(element)) {
                searchItems.add(element);
              }
            }
          });
        } else {
          if (allItems != null) {
            searchItems = allItems; //没有搜索条件，就显示全部。
          }
        }
        return ListView.builder(
          itemBuilder: (BuildContext context, int index) {
            var item = searchItems[index];
            // ${AppStrings.of(context).TheSerial}：${index + 1}\t //序号
            return Material(
              color: backgroundColor(),
              child: InkWell(
                onTap: () {
                  ///搜索条件选中
                  widget.responseCallbackWithT?.call(item);
                  AppRouteHelper.pop(context);
                },
                child: Container(
                  height: 55,
                  child: ListTile(
                    title: Text(
                      "${AppStrings.of(context).JobNumber}：${item.PersonCode}\t${AppStrings.of(context).TheName}：${item.PersonName}\t${AppStrings.of(context).department}：${item.DeptName}",
                      style: AppStyle.textStyleWithItem(),
                    ),
                    // leading: Image.asset(
                    //   item.ImagePath!,
                    //   width: 40,
                    //   height: 40,
                    // ),
                  ),
                ),
              ),
            );
          },
          itemCount: searchItems.length,
        );
      },
    );
  }

  ///点击选择
  Widget _addItemWithTextClick(
      BuildContext context, String leftText, String? rightText,
      {ResponseCallbackWithT<ValueNotifier<String>>? onTap,
      ResponseCallbackWithValueNotifier? mValueNotifier = null}) {
    var textLeft = Text(
      leftText,
      style: AppStyle.textStyleWithPopuItem(),
    );
    ValueNotifier<String> valueNotifier = ValueNotifier(rightText ?? "");
    mValueNotifier?.call(valueNotifier);
    var textRight = ValueListenableBuilder(
      valueListenable: valueNotifier,
      builder: ((context, value, child) {
        return Text(value?.toString() ?? "");
      }),
    );
    // var textRight = Text(
    //   rightText,
    //   style: AppStyle.textStyleWithPopuItem(),
    // );
    var row = Row(
      children: [
        Expanded(
            child: Padding(
          padding: EdgeInsets.only(left: 16, top: 8, bottom: 8),
          child: textLeft,
        )),
        Expanded(
          child: Row(
            children: [
              Expanded(
                child: textRight,
              ),
              AppUi.getRightGo(padding: EdgeInsets.only(right: 16))
            ],
          ),
          flex: 2,
        )
      ],
    );
    return Material(
      color: Colors.white,
      child: Container(
        height: 42,
        child: Column(
          children: [
            Expanded(
                child: InkWell(
                    child: row,
                    onTap: () {
                      onTap?.call(valueNotifier);
                    })),
            Divider(
              height: 1,
              thickness: 1,
              color: AppColors.lineColorWithGrey,
              indent: 16,
              endIndent: 16,
            )
          ],
        ),
      ),
    );
  }

  ///搜索点击按钮
  Widget _addItemWithBtn(BuildContext context, {VoidCallback? onPressed}) {
    var button = Center(
      child: Container(
        height: 38,
        child: MaterialButton(
          height: 38,
          minWidth: px.screenWidth(),
          onPressed: () {
            onPressed?.call();
          },
          //label 右边控件（一般为文本），不能为空
          color: ColorUtils.parseColor('#5484ED'),
          //color 按钮颜色
          splashColor: Colors.black12,
          //splashColor 点击时，飞溅扩散的颜色
          //highlightColor: Colors.red, //highlightColor 点击时按钮颜色
          colorBrightness: Brightness.light,
          //colorBrightness 按钮亮度；Brightness.dark 暗系风格;Brightness.light 高亮(默认)
          shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.all(Radius.circular(8))),
          //shape 形状
          textColor: Colors.white,
          //文本默认颜色
          child: Text(
            AppStrings.of(context).search,
            style: AppStyle.textStyleWithButton(),
          ), //fixme 子控件
        ),
      ),
    );
    return Material(
      color: Colors.white,
      child: Padding(
        child: button,
        padding: EdgeInsets.only(left: 16, right: 16, bottom: 8, top: 8),
      ),
    );
  }
}

class _Presenter {
  ///body视图状态
  StateSetter? setStateBody;

  // ///搜索框视图状态
  // StateSetter? setStateSearch;

  //部门
  String? departmentName = "";
  String? departmentId = "";

  //姓名
  String? searName = "";

  //工号
  String? JobNumber = "";

  List<UserApplicant>? datas = null;

  ///获取部门
  void getdepartment(BuildContext context,
      ResponseCallbackWithT<List<Department>> responseCallbackWithT) {
    UserModel.getDepartments(context, true, (value) {
      //print("=========================================是否成功${value.isSuccessForCode()}");
      if (value.isSuccessForCode()) {
        responseCallbackWithT.call(value.Data!);
      } else {
        //print("错误提示信息：${value?.MsgDetail}");
        AppDialog.showDialogWithInfo(context, content: value?.MsgDetail);
      }
    });
  }

  ///获取搜索数据
  getDatas(BuildContext context,
      ResponseCallbackWithT<List<UserApplicant>> responseCallbackWithT) {
    Future.delayed(Duration(milliseconds: 200)).then((e) {
      //页面初始未加载完成，需要延迟一会儿获取数据
      UserModel.getApplicant(context, true, (value) {
        if (value.isSuccessForCode()) {
          if (value.Data != null && value.Data!.length > 0) {
            datas = value.Data;
            responseCallbackWithT.call(value.Data!);
            setStateBody?.call(() {});
          } else {
            //暂无数据
            AppDialog.showDialogWithInfo(context,
                    content: AppStrings.of(context).noData)
                ?.then((value) {
              AppRouteHelper.pop(context); //关闭当前页面
            });
          }
        } else {
          //异常
          AppDialog.showDialogWithInfo(context, content: value.MsgDetail)
              ?.then((value) {
            AppRouteHelper.pop(context); //关闭当前页面
          });
        }
      });
    });
  }
}
